/*
 * This file is part of the Try! Engine project.
 *
 * Copyright 2010-2011 Emanuele Bertoldi. All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * You should have received a copy of the modified BSD License along with this
 * program. If not, see <http://www.opensource.org/licenses/bsd-license.php>
 */

#include "view3d.h"
#include <cameranode.h>
#include <graphicsmanager.h>
#include <QtGui/QResizeEvent>

using namespace Try;

View3d::View3d(QWidget* parent, CameraNode* camera)
   :    QGLWidget(parent),
        RenderContext(camera),
        m_lastRenderTime(QDateTime::currentDateTime())
{
    this->setObjectName("View3d");
    this->setFocusPolicy(Qt::ClickFocus);
    this->setAcceptDrops(true);
}

View3d::~View3d()
{
}

void View3d::initializeGL()
{
    graphics->registerRenderContext(this);

    if (!this->activeCamera())
    {
        Try::CameraNode* camera = new CameraNode("Camera", "pipelines/forward.pipeline.xml", this->width(), this->height(), 45.0f);

        camera->setTransform(Vector3(0, 10, 30), Vector3(-20, 0, 0), Vector3::Identity);

        this->setActiveCamera(camera);
        this->resizeCameraViewport(this->width(), this->height());
    }
}

void View3d::paintGL()
{
    QDateTime now = QDateTime::currentDateTime();

    graphics->renderAll((double)(now.toMSecsSinceEpoch() - m_lastRenderTime.toMSecsSinceEpoch()));

    m_lastRenderTime = now;
}

void View3d::resizeGL(int width, int height)
{
    this->resizeCameraViewport(width, height);

    std::vector<RenderWindowListener*> listeners = ((Listenable<RenderWindowListener>*)this)->listeners();
    int size = listeners.size();
    for (int i=0; i<size; i++)
        listeners.at(i)->onWindowResized(width, height);
}

void View3d::onUpdateContext()
{
    this->update();
}
